/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package taskmanager2ndedition.client;

import java.util.Date;
import java.util.List;
import taskmanager2ndedition.ClientTaskInfo;

/**
 *
 * @author denaas
 */
public class TaskMonitor implements Runnable {
    private List<ClientTaskInfo> list;
    private ClientController controller;
    private AlarmManager alarmManager;
    private int period;
    private boolean newed;

    public TaskMonitor(AlarmManager manager, ClientController controller){
        alarmManager = manager;
        this.controller = controller;
        this.period = controller.getCheckPeriod();
    }
    
    public synchronized void setTaskList(List<ClientTaskInfo> val){
        newed = true;
        list = val;
        newed = false;
    }
    
    public synchronized List<ClientTaskInfo> getTaskList(){
        while (newed)
            try {
            wait();
        } catch (InterruptedException ex) {
            Thread.currentThread().interrupt();
        }
        return list;
    }
    
    /**
     * Checks the due date of the task and alarms if expired
     * 
     *
     */
    private void check(){
        Date now = new Date();
        for(ClientTaskInfo task: getTaskList()){
            Date theDate = task.getExpirationDate();
            if (task.getStatus() == ClientTaskInfo.TaskStatus.Opened && theDate.before(now))
            {
                task.setStatus(ClientTaskInfo.TaskStatus.InProgress);
                controller.editTask(task);
                alarmManager.alarm(task);
            }
        }
    }
       
    public synchronized void run(){
        while (true){
            try {
                while (getTaskList() == null)
                    wait();
                check();
                Thread.sleep(period);                
            } catch (InterruptedException ex) {
                Thread.currentThread().interrupt();
            }
        }
    }
}
